package com.softeem.spider;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;
import java.time.Duration;

public class HttpUtils {

    /**
     * 读取指定资源为文本
     * @param url
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static String readAsText(String url) {
        //创建默认Http客户端对象
        HttpClient client = HttpClient.newHttpClient();
        //创建Http请求
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(url))   //设置请求资源地址
                .timeout(Duration.ofSeconds(10))    //设置请求超时时间：10秒
                .header("Content-Type", "text/html") //设置请求头
                .GET()  //设置请求方式 GET/POST
                .build();   //构建请求对象

        //创建响应对象
        HttpResponse<String> send = null;
        try {
            send = client.send(req, HttpResponse.BodyHandlers.ofString(Charset.forName("GBK")));
            //获取响应体内容
            return send.body();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取指定资源为输入流
     * @param url
     * @return
     */
    public static InputStream readAsStream(String url){
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(10))
                .GET()
                .build();
        try {
            HttpResponse<InputStream> resp = client.send(req, HttpResponse.BodyHandlers.ofInputStream());
            return resp.body();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


}
